import { NodeCollapseOutlined, NotificationOutlined, PlusOutlined } from '@ant-design/icons';
import { EditableProTable, type EditableProTableProps, ModalForm, ProForm, ProFormDatePicker, ProFormDateTimePicker, ProFormText, } from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useRequest } from '@umijs/max';
import { useDebounceFn } from 'ahooks';
import { Button, Card, Col, Flex, Form, message, Switch, Tag, } from 'antd';
import { forwardRef, type ForwardRefRenderFunction, useCallback, useImperativeHandle, useState, } from 'react';
import { fetchPreEntity } from '@/apis/ygt';
import { type DataOptionType, useCartData, useCostData, useDealData, useReceiveData, } from '@/pages/order/components/CreateForm/CreateForm.data';
import { ColumnMap } from '@/pages/order/Order.data';
import { addRule } from '@/services/ant-design-pro/api';
import './createForm.less';
import { fetchOrderDetail } from '@/apis/order';
import ProFormAutoComplete from '@/components/ProFormAutoComplete';
import { getCustomer } from '@/apis/customer';

interface CreateFormProps {
  reload?: any;
}

export type CreateFormRef = {
  handleEdit: ( id: string ) => void;
};

const CreateForm: ForwardRefRenderFunction<CreateFormRef, CreateFormProps> = (
  props,
  ref,
) => {
  const {reload} = props;

  const [messageApi, contextHolder] = message.useMessage();
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const {run, loading} = useRequest(addRule, {
    manual: true,
    onSuccess: () => {
      messageApi.success('添加成功');
      reload?.();
    },
    onError: () => {
      messageApi.error('添加失败，请重试!');
    },
  });

  const [readonly, setReadonly] = useState(false);
  const [form] = Form.useForm();

  const updateFormField = ( key: string, value: any ) => {
    const fieldName = ColumnMap[key].dataIndex;
    if (!form.getFieldValue(fieldName)) {
      form.setFieldValue(fieldName, value);
    }
  };

  const debouncedSerialChange = useDebounceFn(
    async ( val: string ) => {
      const res = await fetchPreEntity(val);
      if (res.code === 200) {
        const detail: any = res.data || {};
        const vesselVoyageInfo: any = detail.vesselVoyageInfo || {};
        const billInfo: any =
          detail.billInfoList?.length > 0 ? detail.billInfoList[0] : {};
        const packInfo: any = detail.packInfo || {};
        [
          ['driverName', detail.driverName], // 司机
          ['driverPhone', detail.mobile], // 司机手机
          ['vesselName', vesselVoyageInfo.vesseleName], // 船名
          ['voyage', vesselVoyageInfo.voyage], // 航次
          ['billNumber', billInfo.blno], // 提单号
          ['containerNumber', billInfo.ctnno], // 箱号
          ['sealNumber', packInfo.sealno], // 封条号
          ['containerType', packInfo.sizetype], // 箱型
          ['transitPort', packInfo.tranport], // 中转港
          ['shippingLine', `${packInfo.operator}(${packInfo.operatorcode})`], // 船公司
          ['portOpen', vesselVoyageInfo.ctnstart], // 开港时间
          ['portCutoff', vesselVoyageInfo.ctnend], // 截港时间
          ['pickupYard', packInfo.cpcode], // 提箱场站-出运码头
          ['customerPickupYard', packInfo.cpcode], // 客户提箱场站-出运码头
          ['contractNumber', packInfo.costcono], // 合同号
        ].forEach(( [key, value] ) => {
          updateFormField(key, value);
        });
      }
    },
    {wait: 500},
  );
  // 序列号求值
  const handleSerialChange = useCallback(( val: string ) => {
    if (val.length >= 12) {
      debouncedSerialChange.run(val);
    }
  }, []);

  const footer = ( props: any ): any => (
    <ProFormText
      label={props.label + '备注'}
      labelAlign={'left'}
      formItemProps={{
        className: 'mb-0',
      }}
      fieldProps={{
        showCount: true,
        maxLength: 50,
        value: props?.optionData?.remarks,
        onChange: ( e ) => {
          props.optionData.remarks = e.target.value;
          props.setOptionData({...props.optionData});
          // props.setOptionData && props.setOptionData(Object.assign({}, props.optionData, {remarks: e.target.value}));
        },
      }}
    />
  );


  const getTableProps: any = (
    props: Partial<DataOptionType> = {},
  ): EditableProTableProps<any, any> => {

    const options: any[] = props?.options || [];


    const columns: EditableProTableProps<any, any>['columns'] = options.map(
      ( m ) => ({
        title: (
          <Tag bordered={false} color={m.color}>
            {m.label}
          </Tag>
        ),
        key: m.key,
        dataIndex: m.key,
        valueType: 'money',
        fieldProps: {
          changeOnWheel: true,
        },
      }),
    );

    const getFooter = () => footer(props);


    const columnsState: any = {
      defaultValue: options.reduce(( a, b ) => {
        if (b.show === false) {
          a[b.key] = {show: false};
        }
        return a;
      }, {}),
      persistenceType: 'localStorage',
    };

    const cardTableProps: EditableProTableProps<any, any> = {
      style: {width: '100%', marginTop: '-32px'},
      rowKey: 'id',
      search: false,
      size: 'small',
      controlled: true,
      defaultSize: 'large',
      toolbar: {
        className: 'm-toolbar-container',
      },
      options: {
        density: false,
        setting: true,
        reloadIcon: false,
        fullScreen: false,
      },
      recordCreatorProps: false,
      pagination: false,
      scroll: {
        x: 'max-content',
      },
    };

    return {
      columns,
      footer: getFooter,
      columnsState,
      value: [props.optionData],
      onChange: ( values: readonly any[] ) => {
        props.setOptionData!(values[0]);
      },
      editable: {
        editableKeys: [0],
        formProps: {
          layout: 'horizontal',
          //@ts-ignore
          autoFocusFirstInput: false,
        },
      },
      ...cardTableProps,
    };
  };

  const dealData = useDealData();
  const carData = useCartData();
  const costData = useCostData();

  const receiveDate = useReceiveData(
    dealData.total,
    carData.total,
    costData.total,
  );

  const handleSubmit = async ( value: any ) => {
    value.receivableExpenses = JSON.stringify(receiveDate.optionData);
    value.payableExpenses = JSON.stringify(dealData.optionData);
    value.vehicleExpenses = JSON.stringify(carData.optionData);
    value.costExpenses = JSON.stringify(costData.optionData);

    await run({data: value as any});
    reload && reload();
    return true;
  };

  const [open, setOpen] = useState(false);

  const handleEdit = ( id: string ) => {
    setOpen(true);
    fetchOrderDetail(id).then(( res ) => {
      if (res.code === 200) {
        const record = res.data;
        form.setFieldsValue(record);
        const {
          receivableExpenses,
          payableExpenses,
          vehicleExpenses,
          costExpenses,
        } = record;

        if (receivableExpenses) {
          receiveDate.setOptionData(Object.assign({}, receiveDate.optionData, JSON.parse(receivableExpenses)));
        }
        if (payableExpenses) {
          dealData.setOptionData(Object.assign({}, dealData.optionData, JSON.parse(payableExpenses)));
        }
        if (vehicleExpenses) {
          carData.setOptionData(Object.assign({}, carData.optionData, JSON.parse(vehicleExpenses)));
        }
        if (costExpenses) {
          costData.setOptionData(Object.assign({}, costData.optionData, JSON.parse(costExpenses)));
        }
      }
    });
  };

  // 向父组件暴露方法
  useImperativeHandle(ref, () => ({
    handleEdit,
  }));

  const handleCustomerCodeSearch = useCallback(async ( value: string ) => {
    let res = await getCustomer({customerFullName: value});
    return res.data.map(( m: any ) => ({value: m.customerFullName}));
  }, []);

  return (
    <>
      {contextHolder}
      <ModalForm
        layout="horizontal"
        colon={true}
        form={form}
        open={open}
        grid
        readonly={readonly}
        title={
          <Flex gap="middle" align="start" vertical={false}>
            {form.getFieldValue('id') && <Switch
              checkedChildren="编辑"
              unCheckedChildren="详情"
              onChange={setReadonly}
            />}
          </Flex>
        }
        trigger={
          <Button type="primary" icon={<PlusOutlined/>}>
            <FormattedMessage id="pages.searchTable.new" defaultMessage="New"/>
          </Button>
        }
        width="90%"
        modalProps={{
          destroyOnHidden: true,
          okButtonProps: {loading},
          style: {
            top: '50px',
          },
          styles: {
            content: {
              height: 'calc(100vh - 100px)',
              overflowY: 'auto',
            },
            body: {
              height: '85%',
              overflowY: 'auto',
              overflowX: 'hidden',
            },
          },
        }}
        onFinish={handleSubmit}
        submitter={{
          // 配置按钮文本
          searchConfig: {
            resetText: '取消',
            submitText: '提交',
          },
        }}
        onOpenChange={( open ) => {
          setOpen(open);
          if (!open) {
            form.resetFields();
          }
        }}
      >
        <ProForm.Group
          title={<span className="title">业务信息</span>}
          collapsible
          rowProps={{
            gutter: [16, 16],
          }}
        >
          <ProFormText name="id" hidden></ProFormText>
          <ProFormText
            label="序列号"
            name={ColumnMap.serialNumber.dataIndex}
            width="md"
            colProps={{span: 24}}
            rules={[{required: true}]}
            onMetaChange={( meta ) => {
              console.log('[MLog] meta:', meta);
            }}
            fieldProps={{
              prefix: <NodeCollapseOutlined style={{color: '#1890ff'}}/>,
              onChange: ( e ) => {
                handleSerialChange(e.target.value);
              },
            }}
          />

          <Col span={24}>
            <Card size={'small'}>
              <ProForm.Group title={'客户订单信息'}>
                <ProFormText
                  label="合同号"
                  name={ColumnMap.contractNumber.dataIndex}
                  width={'md'}
                  colProps={{xl: 8}}
                />
                <ProFormDatePicker
                  label="接单日期"
                  name={ColumnMap.orderDate.dataIndex}
                  width="md"
                  colProps={{xl: 8}}
                  rules={[{required: true}]}
                />

                <ProFormAutoComplete
                  name={ColumnMap.customerCode.dataIndex}
                  key="customerCode"
                  label="客户简称"
                  colProps={{xl: 8}}
                  width={'md'}
                  rules={[{required: true, message: '请输入客户简称'}]}
                  search={handleCustomerCodeSearch}
                >
                </ProFormAutoComplete>

              </ProForm.Group>
            </Card>
          </Col>

          <Col span={24}>
            <Card size={'small'}>
              <ProForm.Group title={'码头船期信息'}>
                <ProFormText
                  label="船名"
                  name={ColumnMap.vesselName.dataIndex}
                  width="md"
                  colProps={{xl: 6}}
                />
                <ProFormText
                  label="航次"
                  fieldProps={{}}
                  name={ColumnMap.voyage.dataIndex}
                  width="md"
                  colProps={{xl: 6}}
                />

                <ProFormAutoComplete
                  label="船公司"
                  colProps={{xl: 6}}
                  name={ColumnMap.shippingLine.dataIndex}
                />

                <ProFormText
                  label="中转港"
                  name={ColumnMap.transitPort.dataIndex}
                  width="md"
                  colProps={{xl: 6}}
                />

                <ProFormDateTimePicker
                  label="开港时间"
                  name={ColumnMap.portOpen.dataIndex}
                  width={'xl'}
                  colProps={{xl: 6}}
                />

                <ProFormDateTimePicker
                  label="截港时间"
                  name={ColumnMap.portCutoff.dataIndex}
                  width={'md'}
                  colProps={{xl: 6}}
                />
              </ProForm.Group>
            </Card>
          </Col>

          <Col span={24}>
            <Card size={'small'}>
              <ProForm.Group title={'拆装箱信息'}>
                <ProFormText
                  label="箱号"
                  name={ColumnMap.containerNumber.dataIndex}
                  width="md"
                  colProps={{xl: 6}}
                />

                <ProFormText
                  label="封条号"
                  name={ColumnMap.sealNumber.dataIndex}
                  width="md"
                  colProps={{xl: 6}}
                />

                <ProFormDateTimePicker
                  label="做箱时间"
                  name={ColumnMap.stuffingTime.dataIndex}
                  colProps={{xl: 6}}
                />

                <ProFormAutoComplete
                  label="箱型"
                  colProps={{xl: 6}}
                  name={ColumnMap.containerType.dataIndex}
                  rules={[{required: true, message: ''}]}
                />

                <ProFormAutoComplete
                  label="拆/装箱地点"
                  colProps={{xl: 12}}
                  name={ColumnMap.location.dataIndex}
                />

                <ProFormText
                  label="拆/装箱地址"
                  name={ColumnMap.address.dataIndex}
                  colProps={{xl: 12}}
                />
              </ProForm.Group>
            </Card>
          </Col>

          <Col span={24}>
            <Card size={'small'}>
              <ProForm.Group title={'提箱还箱信息'}>
                <ProFormText
                  label="提单号"
                  name={ColumnMap.billNumber.dataIndex}
                  width="md"
                  colProps={{xl: 6}}
                />

                <ProFormAutoComplete
                  label="提箱场站"
                  name={ColumnMap.pickupYard.dataIndex}
                  colProps={{xl: 6}}
                />

                <ProFormAutoComplete
                  label="客户提箱场站"
                  name={ColumnMap.customerPickupYard.dataIndex}
                  colProps={{xl: 6}}
                />

                <ProFormAutoComplete
                  label="还箱场站"
                  name={ColumnMap.returnYard.dataIndex}
                  colProps={{xl: 6}}
                />
              </ProForm.Group>
            </Card>
          </Col>

          <Col span={24}>
            <Card size={'small'}>
              <ProForm.Group title={'司机信息'}>
                <ProFormAutoComplete
                  label="司机"
                  name={ColumnMap.driverName.dataIndex}
                  colProps={{xl: 6}}
                />
                <ProFormAutoComplete
                  label="车牌号"
                  name={ColumnMap.licensePlate.dataIndex}
                  colProps={{xl: 6}}
                />
    
                <ProFormText
                  label="司机手机"
                  name={ColumnMap.driverPhone.dataIndex}
                  width="md"
                  colProps={{xl: 6}}
                />
              </ProForm.Group>
            </Card>
          </Col>

          <Col span={24} style={{marginBottom: 30}}>
            <Card size={'small'}>
              <ProForm.Group title={'备注信息'}>
                <ProFormText
                  label="托运单备注"
                  name={ColumnMap.consignmentNote.dataIndex}
                  colProps={{xl: 12}}
                  fieldProps={{
                    showCount: true,
                    maxLength: 50,
                  }}
                />
                <ProFormText
                  label="大表备注"
                  name={ColumnMap.remarks.dataIndex}
                  colProps={{xl: 12}}
                  fieldProps={{
                    showCount: true,
                    maxLength: 50,
                  }}
                />
              </ProForm.Group>
            </Card>
          </Col>
        </ProForm.Group>

        {[receiveDate, dealData, carData, costData].map(( item ) => (
          <>
            <ProForm.Group title={item.title} collapsible key={item.label}>
              {
                readonly
                  ? <>
                    {
                      item.options.map(m => <Col span={4}>
                        <ProFormText
                          label={m.label}
                          labelCol={{span: 12}}
                          fieldProps={{
                            value: item.optionData[m.key],
                          }}
                        />
                      </Col>)
                    }
                    {
                      <Flex justify={'space-around'} align={'center'} style={{
                        width: '100%',
                        padding: '0 20px',
                        marginTop: -10,
                        marginBottom: 20,
                        background: 'rgba(245, 245, 245,0.8)',
                      }}>
                        <NotificationOutlined style={{color: 'rgb(24, 144, 255)'}}/>
                        {
                          footer(item)
                        }
                      </Flex>
                    }
                  </>
                  :
                  <>
                    <EditableProTable
                      {...getTableProps(item)}
                    ></EditableProTable>
                  </>
              }
            </ProForm.Group>
          </>
        ))}
      </ModalForm>
    </>
  );
};

export default forwardRef(CreateForm);
